<!--
  @author:  long
  @date:    2023/4/7
  @file:    指标考评
  @require:
-->
<template>
  <div class="indicatorEvaluation">
    <FixedOperation>
      <div class="flex items-center justify-between">
        <span class="text-xl font-semibold">按指标考评</span>
        <!-- 内容 -->
        <div class="text-right">
          <el-button
            type="primary"
            :disabled="loading"
            @click="handlePre"
            v-if="isActive > 0"
            >上一条</el-button
          >
          <el-button
            type="success"
            @click="handleNext"
            :disabled="loading"
            v-if="isActive < indicatorsIds.length - 1"
            >下一条</el-button
          >
          <el-button type="primary" @click="handleIndicatorSave"
            >保存</el-button
          >
          <el-button type="danger" @click="handleBack">返回列表</el-button>
        </div>
      </div>
    </FixedOperation>
    <div class="app-container">
      <el-row v-loading="loading">
        <el-col :span="12">
          <title-name
            class="mb-6"
            margin-left="0"
            icon="i-carbon-bookmark-filled"
            title="指标信息"
          ></title-name>
          <div class="pr-5">
            <el-row v-for="(item, index) in items" :key="index" class="mb-2">
              <el-col :span="8" class="text-right text-lg"
                >{{ item.label }}：</el-col
              >
              <el-col :span="16" class="text-lg">
                <template v-if="item.prop == 'scoreMethod'">
                  <dict-tag
                    :options="scoring_method"
                    :value="assessInfo.scoreMethod"
                  />
                </template>
                <template v-else-if="item.prop == 'frequency'">
                  <dict-tag
                    :options="examine_frequency"
                    :value="assessInfo.frequency"
                  />
                </template>
                <template v-else-if="item.prop == 'unit'">
                  <dict-tag
                    :options="indicator_unit"
                    :value="assessInfo.unit"
                  />
                </template>
                <template v-else-if="item.prop == 'userName'">
                  {{ userStore.user.nickName }}
                </template>
                <template v-else> {{ assessInfo[item.prop] }}</template>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <el-col :span="12">
          <title-name class="mb-6" margin-left="0" title="考评"></title-name>
          <el-form :model="form">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="统一完成情况：">
                  <el-input
                    :disabled="tableData.length == 0"
                    @input="completionInput"
                    v-model="form.unifiedCompletionStatus"
                  ></el-input> </el-form-item
              ></el-col>
              <el-col :span="12"
                ><el-form-item label="统一评分：">
                  <el-input
                    v-model="form.unifiedScore"
                    v-if="assessInfo.scoreMethod == '1'"
                    @change="
                      val => {
                        handleScoreInputChange(val)
                      }
                    "
                  ></el-input>
                  <el-input-number
                    v-else
                    :min="
                      assessInfo.scoreMethod == '1'
                        ? assessInfo.score == '减分项' ||
                          assessInfo.score == '加/减分项'
                          ? -9999
                          : 0
                        : 0
                    "
                    :max="
                      assessInfo.scoreMethod == '3'
                        ? assessInfo.score * 1 - assessInfo.basicScore * 1
                        : assessInfo.scoreMethod == '1'
                        ? assessInfo.scope == '加分项'
                          ? 9999
                          : assessInfo.score * 1
                        : assessInfo.score * 1
                    "
                    :disabled="
                      tableData.length == 0 || assessInfo.scoreMethod == '2'
                    "
                    v-model="form.unifiedScore"
                    @input="handleUnifiedRatingChange"
                  ></el-input-number> </el-form-item
              ></el-col>
            </el-row>
          </el-form>
          <el-table
            :data="tableData"
            v-loading="loading"
            border
            :header-cell-style="{ textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
          >
            <el-table-column label="被考核人" prop="appraiseeName">
            </el-table-column>
            <el-table-column label="计分方式">
              <template #default="scope">
                <dict-tag
                  :options="scoring_method"
                  :value="scope.row.scoreMethod"
                />
                <!--      计算百分比        -->
                <div v-if="scope.row.scoreMethod == '2'">
                  {{
                    scope.row.assessDescription == '' ||
                    scope.row.assessDescription == null
                      ? '——'
                      : Math.round(
                          ((scope.row.assessDescription * 1) /
                            assessInfo.targetValue) *
                            10000
                        ) /
                          100 +
                        '%'
                  }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="完成情况" width="150">
              <template #default="scope">
                <el-input
                  v-model="scope.row.assessDescription"
                  :type="scope.row.scoreMethod == '2' ? 'number' : 'text'"
                  @input="
                    val => {
                      scoreDescriptionSelfInput(val, scope.row)
                    }
                  "
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              label="自评得分"
              prop="finalScoreSelf"
            ></el-table-column>

            <el-table-column label="评分">
              <template #default="scope">
                <el-input
                  v-model="scope.row.assessScore"
                  v-if="scope.row.scoreMethod == '1'"
                  @change="
                    val => {
                      scoreInputChange(scope.row, val)
                    }
                  "
                ></el-input>
                <el-input-number
                  v-else
                  :min="
                    scope.row.scoreMethod == '1'
                      ? assessInfo.score == '减分项' ||
                        assessInfo.score == '加/减分项'
                        ? -9999
                        : 0
                      : 0
                  "
                  :max="
                    scope.row.scoreMethod == '3'
                      ? assessInfo.score * 1 - scope.row.basicScore * 1
                      : scope.row.scoreMethod == '1'
                      ? assessInfo.scope == '加分项'
                        ? 9999
                        : assessInfo.score * 1
                      : assessInfo.score * 1
                  "
                  :disabled="scope.row.scoreMethod == '2'"
                  v-model="scope.row.assessScore"
                  @input="
                    val => {
                      handleGradeBlur(scope.row, val)
                    }
                  "
                  @change="
                    val => {
                      handleGradeInput(scope.row, val)
                    }
                  "
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="得分" prop="finalAssessScore">
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup name="IndicatorEvaluation">
import { isNumberStr } from '@/utils'

import useUserStore from '@/store/modules/user'
import { getCurrentInstance } from 'vue'
import {
  getAssessItemByIndicator,
  getAssessItemIdsByIndicator,
  updateAssessScoreByIndicator
} from '@/api/officeManage/appraisal'

const userStore = useUserStore()
const { proxy } = getCurrentInstance()
const { scoring_method, indicator_unit, examine_frequency } = proxy.useDict(
  'scoring_method',
  'indicator_unit',
  'examine_frequency'
)

const props = defineProps({
  info: {
    type: Object,
    default: () => {}
  }
})

const data = reactive({
  loading: false,
  assessInfo: {},
  tableData: [],
  form: {},
  items: [
    { label: '一级指标', prop: 'firstLevel' },
    { label: '二级指标', prop: 'secondLevel' },
    { label: '考核频率', prop: 'frequency' },
    { label: '指标说明及工作内容、工作要求', prop: 'content' },
    { label: '指标单位', prop: 'unit' },
    { label: '指标值', prop: 'targetValue' },
    { label: '考核评分标准', prop: 'scoreStandard' },
    { label: '分值权重', prop: 'score' },
    { label: '基础分', prop: 'basicScore' },
    { label: '计分方式', prop: 'scoreMethod' },
    { label: '考核人', prop: 'userName' }
  ],
  isActive: 0, //当前选择
  indicatorsIds: [] //指标ids
})
const { loading, items, tableData, form, assessInfo, isActive, indicatorsIds } =
  toRefs(data)

const emits = defineEmits(['switchModule'])

//计算评分
const scoreDescriptionSelfInput = (val, row) => {
  if (assessInfo.value.scoreMethod == '2') {
    //   计算百分比
    let percentage =
      Math.round(
        ((row.assessDescription * 1) / assessInfo.value.targetValue) * 10000
      ) / 100
    console.info('percentage', percentage)
    let rate = percentage * 0.01
    switch (assessInfo.value.scoreStandardCode) {
      case '1':
        if (percentage >= 60) {
          row.assessScore =
            rate * assessInfo.value.score > assessInfo.value.score
              ? assessInfo.value.score
              : rate * assessInfo.value.score
        } else {
          row.assessScore = 0
        }
        break
      case '2':
        if (percentage >= 60) {
          row.assessScore =
            rate * assessInfo.value.score > assessInfo.value.score
              ? assessInfo.value.score
              : rate * assessInfo.value.score
        } else if (percentage == 0) {
          row.assessScore = 0 - assessInfo.value.score
        } else {
          row.assessScore = 0
        }
        break
      case '3':
        row.assessScore =
          rate * assessInfo.value.score > assessInfo.value.score
            ? assessInfo.value.score
            : rate * assessInfo.value.score
        break
      case '4':
        if (percentage >= 60) {
          row.assessScore =
            rate * assessInfo.value.score > assessInfo.value.score
              ? assessInfo.value.score
              : rate * assessInfo.value.score
        } else if (percentage == 0) {
          row.assessScore = 0 - assessInfo.value.score
        } else {
          row.assessScore = 0
        }
        break
      case '5':
        if (percentage >= 60) {
          row.assessScore =
            rate * assessInfo.value.score > assessInfo.value.score * 1.2
              ? assessInfo.value.score * 1.2
              : rate * assessInfo.value.score
        } else {
          row.assessScore = 0
        }
        break
      case '6':
        if (percentage >= 60) {
          row.assessScore =
            rate * assessInfo.value.score > assessInfo.value.score * 1.3
              ? assessInfo.value.score * 1.3
              : rate * assessInfo.value.score
        } else {
          row.assessScore = 0
        }
        break
    }
    row.assessScore = row.assessScore.toFixed(2)

    handleGradeInput(row, row.assessScore)
  }
}

/**
 * 统一完成情况input
 */
const completionInput = val => {
  if (tableData.value.length > 0) {
    if (assessInfo.value.scoreMethod == '2') {
      //   计算百分比
      let percentage =
        Math.round(((val * 1) / assessInfo.value.targetValue) * 10000) / 100
      console.info('percentage', percentage)
      let rate = percentage * 0.01
      let assessScore = 0
      switch (assessInfo.value.scoreStandardCode) {
        case '1':
          if (percentage >= 60) {
            assessScore =
              rate * assessInfo.value.score > assessInfo.value.score
                ? assessInfo.value.score
                : rate * assessInfo.value.score
          } else {
            assessScore = 0
          }
          break
        case '2':
          if (percentage >= 60) {
            assessScore =
              rate * assessInfo.value.score > assessInfo.value.score
                ? assessInfo.value.score
                : rate * assessInfo.value.score
          } else if (percentage == 0) {
            assessScore = 0 - assessInfo.value.score
          } else {
            assessScore = 0
          }
          break
        case '3':
          assessScore =
            rate * assessInfo.value.score > assessInfo.value.score
              ? assessInfo.value.score
              : rate * assessInfo.value.score
          break
        case '4':
          if (percentage >= 60) {
            assessScore =
              rate * assessInfo.value.score > assessInfo.value.score
                ? assessInfo.value.score
                : rate * assessInfo.value.score
          } else if (percentage == 0) {
            assessScore = 0 - assessInfo.value.score
          } else {
            assessScore = 0
          }
          break
        case '5':
          if (percentage >= 60) {
            assessScore =
              rate * assessInfo.value.score > assessInfo.value.score * 1.2
                ? assessInfo.value.score * 1.2
                : rate * assessInfo.value.score
          } else {
            assessScore = 0
          }
          break
        case '6':
          if (percentage >= 60) {
            assessScore =
              rate * assessInfo.value.score > assessInfo.value.score * 1.3
                ? assessInfo.value.score * 1.3
                : rate * assessInfo.value.score
          } else {
            assessScore = 0
          }
          break
      }
      assessScore = assessScore.toFixed(2)
      tableData.value.forEach(item => {
        item.assessDescription = val
        item.assessScore = assessScore
        item.finalAssessScore = assessScore
      })
    } else {
      tableData.value.forEach(item => {
        item.assessDescription = val
      })
    }
  }
}

// 表格赋值
const setTableDataAssessScore = value => {
  tableData.value.forEach(item => {
    item.assessScore = value

    handleGradeInput(item, value)
  })
}

/**
 * 录入情况下的统一评分
 */
const handleScoreInputChange = val => {
  if (tableData.value.length > 0) {
    if (!isNumberStr(val) && val != '') {
      proxy.$modal.msgError('请输入数字，最多保留两位小数')
      setTableDataAssessScore(null)
    } else if (val == '') {
      setTableDataAssessScore(null)
    } else {
      let inputVal = val * 1
      switch (assessInfo.value.score) {
        //加分项
        case '加分项':
          if (inputVal < 0) {
            proxy.$modal.msgError('请输入正数或0，最多保留两位小数')

            setTableDataAssessScore(null)
          } else {
            setTableDataAssessScore(val)
          }
          break
        //加减分项
        case '加/减分项':
          setTableDataAssessScore(val)
          break
        //减分项
        case '减分项':
          console.info('123')
          if (inputVal > 0) {
            proxy.$modal.msgError('请输入负数或0，最多保留两位小数')
            setTableDataAssessScore(null)
          } else {
            setTableDataAssessScore(val)
          }
          break
        default:
          if (inputVal < 0) {
            proxy.$modal.msgError('请输入正数或0，最多保留两位小数')
            setTableDataAssessScore(null)
            return
          } else if (inputVal > assessInfo.value.score * 1) {
            setTableDataAssessScore(assessInfo.value.score)
          } else {
            setTableDataAssessScore(val)
          }
          break
      }
    }
  }
}

/**
 * 统一评分input
 */
const handleUnifiedRatingChange = val => {
  console.info('val', val)

  if (tableData.value.length > 0) {
    //加分
    if (assessInfo.value.scoreMethod == '3') {
      tableData.value.forEach(item => {
        let value =
          val >= assessInfo.value.score - assessInfo.value.basicScore
            ? assessInfo.value.score - assessInfo.value.basicScore
            : val
        console.info('value', value)
        item.assessScore = value

        handleGradeInput(item, value)
      })
    } else {
      tableData.value.forEach(item => {
        let value =
          val >= assessInfo.value.score
            ? assessInfo.value.score - assessInfo.value.basicScore
            : val < 0
            ? 0
            : val
        item.assessScore = value

        handleGradeInput(item, value)
      })
    }
  }
}

const handleGradeBlur = (row, val) => {
  if (val === null) {
    row.finalAssessScore = ''
    return
  }
}

/**
 * @description: 录入情况下评分input框change方法
 */
const scoreInputChange = (row, val) => {
  if (!isNumberStr(val) && val != '') {
    proxy.$modal.msgError('请输入数字，最多保留两位小数')
    row.assessScore = null
    handleGradeInput(row, null)
  } else if (val == '') {
    handleGradeInput(row, null)
  } else {
    let inputVal = val * 1
    console.info('assessInfo.value.score', assessInfo.value.score)

    switch (assessInfo.value.score) {
      //加分项
      case '加分项':
        if (inputVal < 0) {
          proxy.$modal.msgError('请输入正数或0，最多保留两位小数')
          row.assessScore = null

          handleGradeInput(row, null)
        } else {
          handleGradeInput(row, val)
        }
        break
      //加减分项
      case '加/减分项':
        handleGradeInput(row, val)
        break
      //减分项
      case '减分项':
        if (inputVal > 0) {
          proxy.$modal.msgError('请输入负数或0，最多保留两位小数')
          row.assessScore = null

          handleGradeInput(row, null)
        } else {
          handleGradeInput(row, val)
        }
        break
      default:
        if (inputVal < 0) {
          proxy.$modal.msgError('请输入正数或0，最多保留两位小数')
          row.assessScore = null

          handleGradeInput(row, null)
        } else if (inputVal > assessInfo.value.score * 1) {
          row.assessScore = assessInfo.value.score
          handleGradeInput(row, assessInfo.value.score)
        } else {
          handleGradeInput(row, val)
        }
        break
    }
  }
}

/**
 * @description: 评分输入框input方法
 */
const handleGradeInput = (row, val) => {
  if (val === null) {
    row.finalAssessScore = ''
    return
  }
  let inputVal = val * 1
  switch (assessInfo.value.scoreMethod) {
    //录入
    case '1':
      row.finalAssessScore = inputVal
      break
    // 完成率
    case '2':
      row.finalAssessScore = inputVal
      break
    //加分
    case '3':
      row.finalAssessScore = assessInfo.value.basicScore + inputVal
      break
    //减分
    case '4':
      console.info('val', val)
      console.info('row.score', assessInfo.value.score)
      console.info('row.score - inputVal', assessInfo.value.score - inputVal)
      console.info('final_score_self', row.finalAssessScore)
      row.finalAssessScore = assessInfo.value.score - inputVal
      break

    default:
      break
  }
}

/**
 * 保存
 */
const handleIndicatorSave = type => {
  loading.value = true
  let params = {
    appraiseeId: userStore.user.userId,
    id: indicatorsIds.value[isActive.value]
  }
  params.updateAssessScoreItemDtoList = tableData.value.map(item => {
    return {
      appraiseeId: item.appraiseeId,
      finalAssessScore: item.finalAssessScore,
      assessDescription: item.assessDescription,
      assessScore: item.assessScore
    }
  })
  // 更新叫考核他评分数
  updateAssessScoreByIndicator(params)
    .then(res => {
      if (res.code === 200) {
        if (type == 'pre') {
          form.value = {}
          isActive.value = --isActive.value
          getAssessItemByIndicatorApi(indicatorsIds.value[isActive.value])
        } else if (type == 'next') {
          form.value = {}
          isActive.value = ++isActive.value
          getAssessItemByIndicatorApi(indicatorsIds.value[isActive.value])
        } else {
          proxy.$modal.msgSuccess(res.msg)
        }
        loading.value = false
      }
    })
    .catch(err => {
      loading.value = false
    })
}

/**
 * 查询上一条
 */
const handlePre = () => {
  handleIndicatorSave('pre')
}

/**
 * 查询下一条
 */
const handleNext = () => {
  handleIndicatorSave('next')
}

/**
 * 返回
 */
const handleBack = () => {
  emits('switchModule', 'evaluationList', 'other', 'target')
}

/**
 * 获取绩效考核指标Id
 */
const getAssessItemIdsByIndicatorApi = () => {
  let params = {
    assessorId: userStore.user.userId
  }

  getAssessItemIdsByIndicator(params).then(res => {
    console.info('res', res)
    if (res.data != null > 0) {
      indicatorsIds.value = res.data
      if (Object.keys(props.info).length != 0) {
        isActive.value = res.data.findIndex(item => item == props.info.id)
      }
      let id = res.data[isActive.value]

      getAssessItemByIndicatorApi(id)
    }
  })
}

/**
 * 根据绩效考核指标Id获取详细指标内容
 */
const getAssessItemByIndicatorApi = id => {
  loading.value = true
  let params = {
    assessorId: userStore.user.userId,
    indicatorsId: id
  }
  getAssessItemByIndicator(params)
    .then(res => {
      assessInfo.value = res.data
      tableData.value = res.data.bizAssessItemVoList
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 初始化
 */

const init = () => {
  getAssessItemIdsByIndicatorApi()
}
init()
</script>

<style scoped lang="scss"></style>
